package com.guoj.easyweb.app.controller;

/**
 * @作者: guoj
 * @日期: 2019/6/21 16:33
 * @描述:
 */

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.guoj.easyweb.common.exception.CustomException;
import com.guoj.easyweb.common.utils.*;
import com.guoj.easyweb.common.validator.ValidatorUtils;
import com.guoj.easyweb.entity.TbUser;
import com.guoj.easyweb.form.AppLoginForm;
import com.guoj.easyweb.form.LoginForm;
import com.guoj.easyweb.service.ITbUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @作者: guoj
 * @日期: 2019/6/21 16:18
 * @描述: app访问控制器
 */
@Api(value = "User-API",tags = {"用户信息接口"})
@RestController
@RequestMapping("/app")
public class UserController {

	@Autowired
	private ITbUserService userService;
	@Autowired
	private JwtUtils jwtUtils;

	/**
	 * 登录成功返回token
	 * @param loginForm
	 * @return
	 */
	@ApiOperation(value = "登录", notes = "用户登录，登录成功返回token。")
	@PostMapping("/login")
	public ResponseEntity login(@RequestBody AppLoginForm loginForm) {
		// 表单校验
		ValidatorUtils.validateEntity(loginForm);

		// 用户登录
		TbUser user = userService.appLogin(loginForm);
		System.out.println("[userId]: " + user.getId());
		// 生成token
		String token = jwtUtils.generateToken(user.getId());
		System.out.println("[token]: " + token);

		Map<String, Object> map = new HashMap<>();
		map.put("token", token);
		map.put("expire", jwtUtils.getExpire());
		System.out.println("[map]: " + map);

		return new ResponseEntity(true, StatusCode.OK, "登录成功", map);
	}

	/**
	 * 用户列表，分页。
	 * -- pageNum和pageSize是前端根据layui.table规范自定义的名称
	 * @return
	 */
	@ApiOperation(value = "获取用户分页列表", notes = "根据[页码]和[每页记录数]获取用户分页列表，返回[获取用户分页列表成功]或[获取用户分页列表失败]的json格式数据。")
	@GetMapping("/userList/{pageNum}/{pageSize}")
	public LayTableEntity userList(@PathVariable("pageNum") Integer pageNum,
			@PathVariable("pageSize") Integer pageSize) {
		System.out.println("====================分页参数======================");
		System.out.println("当前页：" + pageNum);
		System.out.println("每页显示条数：" + pageSize);
		System.out.println("====================分页参数======================");
		Page<TbUser> page = new Page<>(pageNum, pageSize);
		QueryWrapper<TbUser> queryWrapper = new QueryWrapper<>();
		queryWrapper.isNotNull("id");
		IPage<TbUser> userList = userService.getBaseMapper().selectPage(page, queryWrapper);
		if (userList == null) {
			return new LayTableEntity(StatusCode.ERROR, "获取用户分页列表失败", null, null);
		}
		return new LayTableEntity(StatusCode.LAYUI_OK, "获取用户分页列表成功", userList.getTotal(), userList.getRecords());
	}

	/**
	 * 获取所有用户列表
	 * @return
	 */
	@ApiOperation(value = "获取用户列表", notes = "获取用户列表，返回[获取用户列表成功]或[获取用户列表失败]的json格式数据。")
	@GetMapping("/userList")
	public ResponseEntity getUser() {
		List<TbUser> userList = userService.getBaseMapper().selectList(new QueryWrapper<TbUser>().isNotNull("id"));
		if (userList == null) {
			return new ResponseEntity(true, StatusCode.ERROR, "获取用户列表失败", userList);
		}
		return new ResponseEntity(true, StatusCode.OK, "获取用户列表成功", userList);
	}

	/**
	 * 添加用户
	 * @param user
	 * @return
	 */
	@ApiOperation(value = "添加用户", notes = "添加用户，返回[添加用户成功]或[添加用户失败]的json格式数据。")
	@PostMapping(value = "/addUser")
	public ResponseEntity addUser(@RequestBody TbUser user) {
		System.out.println("################ user: " + user);
		if (user == null) {
			return new ResponseEntity(false, StatusCode.ERROR, "要添加的用户信息为空！");
		}
		int result = userService.addUser(user);
		if (result == 0) {
			return new ResponseEntity(false, StatusCode.ERROR, "添加用户失败！");
		}
		return new ResponseEntity(true, StatusCode.OK, "添加用户成功！");
	}

	/**
	 * 修改用户状态：启用/禁用
	 * @param id
	 * @param flag
	 * @return
	 */
	@ApiOperation(value = "修改用户状态", notes = "修改用户，返回[修改用户状态成功]或[修改用户状态失败]的json格式数据。")
	@PutMapping(value = "/switchStatus")
	public ResponseEntity switchStatus(@RequestParam(value = "id", defaultValue = "0") long id,
			@RequestParam(value = "flag", defaultValue = "0") Integer flag) {
		System.out.println("============switch启用/禁用============");
		System.out.println(id);
		System.out.println(flag);
		System.out.println("============switch启用/禁用============");
		TbUser user = new TbUser();
		user.setId(id);
		user.setFlag(flag);
		boolean result = userService.updateById(user);
		if (!result) {
			return new ResponseEntity(false, StatusCode.ERROR, "修改用户状态失败！");
		}
		return new ResponseEntity(true, StatusCode.OK, "修改用户状态成功！");
	}

	/**
	 * 根据ID删除用户
	 * @param id
	 * @return
	 */
	@ApiOperation(value = "删除用户", notes = "删除用户，返回[删除用户成功]或[删除用户失败]的json格式数据。")
	@DeleteMapping(value = "/delUser")
	public ResponseEntity delUserById(@RequestParam(value = "id") String id) {

		if (StringUtils.isBlank(id)) {
			return new ResponseEntity(false, StatusCode.ERROR, "没有可删除的用户！");
		}

		int result = userService.getBaseMapper().deleteById(id);
		if (result == 0) {
			return new ResponseEntity(false, StatusCode.ERROR, "删除用户失败，请检查日志！");
		}

		return new ResponseEntity(true, StatusCode.OK, "删除用户成功！");
	}
}
